package com.reform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.reform.pojo.project.ProjectRecord;
import com.reform.mapper.ProjectRecordMapper;
import com.reform.res.Result;
import com.reform.res.ResultCode;
import com.reform.service.IProjectRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reform.utils.JSONToArrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mortale
 * @since 2021-11-02
 */
@Service
public class ProjectRecordServiceImpl extends ServiceImpl<ProjectRecordMapper, ProjectRecord> implements IProjectRecordService {

    @Autowired
    ProjectRecordMapper projectRecordMapper;

    @Override
    public Result addProject(String projectRecords) {
        List<ProjectRecord> projectRecordList = JSONToArrUtils.jsonToArr(projectRecords, ProjectRecord.class);
        if (projectRecordList == null) {
            return Result.failure(ResultCode.PARAM_JSON_IS_WRONG);
        }

        int code = 0;

        for (ProjectRecord projectRecord : projectRecordList) {
            code += projectRecordMapper.insert(projectRecord);
        }
        if (code == projectRecordList.size()) {
            return Result.success(ResultCode.SUCCESS);
        }
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public Result deleteProject(String batchId) {
        int code = projectRecordMapper.delete(new QueryWrapper<ProjectRecord>().eq("batch_id", batchId));
        if (code > 0) {
            return Result.success(ResultCode.SUCCESS);
        }
        return Result.failure(ResultCode.FAILURE);
    }

    @Override
    public Result getAllProject() {
        return Result.success(ResultCode.SUCCESS, projectRecordMapper.selectList(null));
    }

    @Override
    public Result getProjectByBatchId(String batchId) {
        return Result.success(ResultCode.SUCCESS, projectRecordMapper.selectList(new QueryWrapper<ProjectRecord>().eq("batch_id", batchId)));
    }

    @Override
    public Result deleteProjects(String batchIdList) {
        List<String> batchIds = JSONToArrUtils.jsonToArr(batchIdList, String.class);
        if (batchIds == null) {
            return Result.failure(ResultCode.PARAM_JSON_IS_WRONG);
        }
        int code = 0;
        for (String batchId : batchIds) {
            code += projectRecordMapper.delete(new QueryWrapper<ProjectRecord>().eq("batch_id", batchId));
        }
        if (code == batchIds.size()) {
            return Result.success(ResultCode.SUCCESS);
        }
        return Result.failure(ResultCode.FAILURE);
    }
}
